<script setup name="BizUserInfoIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import FormMode from "./modules/FormMode/index.vue";
import { addBizElectronFence, findMaxSort } from "@/api/biz/bizElectronFence";
import { parseTime } from "@/utils/aidex";
import {
  listBizUserInfo,
  delBizUserInfo,
  exportBizUserInfo
} from "@/api/biz/bizUserInfo";
import Electronfence from "../electronfence/index.vue";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();
const mapElectronfence = ref();
const data = ref({
  form: { lng: 111.361, lat: 30.64441 },
  loading: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: ""
  },
  // 搜索
  search: {
    nikeName: "",
    phone: "",
    name: "",
    type: "1"
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: [],
  userInfo: "",
  elecProps: {
    visible: false
  }
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
  getPosition();
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});

// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
function sortChange(prop, order) {
  onSortChange(prop, order).then(() => getDataList());
}
// 查询
function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.nikeName && (params.nikeName = data.value.search.nikeName);
  data.value.search.name && (params.name = data.value.search.name);
  data.value.search.phone && (params.nikeName = data.value.search.phone);
  data.value.search.type && (params.type = data.value.search.type);
  listBizUserInfo(params).then((res) => {
    data.value.loading = false;
    data.value.dataList = res.data.list;
    pagination.value.total = res.data.total;
  });
}

// 编辑
function onEdit(row) {
  data.value.formMode = "drawer";
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.id
      }
    });
  } else {
    data.value.formModeProps.id = row.id;
    data.value.formModeProps.visible = true;
  }
}
// 添加
function onAdd() {
  data.value.formModeProps.id = "";
  data.value.formMode = "dialog";
  data.value.formModeProps.visible = true;
}
// 批量删除 单独删除
function onDel(row) {
  const ids =
    row.id ||
    data.value.batch.selectionDataList.map((item) => {
      return item.id;
    });
  const names =
    row.name ||
    data.value.batch.selectionDataList.map((item) => {
      return item.name;
    });
  if (ids.length > 0) {
    ElMessageBox.confirm("确认删除「" + names + "」吗？", "确认信息")
      .then(() => {
        delBizUserInfo(ids).then((res) => {
          getDataList();
          if (res.code == 200)
            ElMessage.success({
              message: "删除成功",
              center: true
            });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning({ message: "请选择数据", center: true });
  }
}
function handleCommand(command) {
  if (command.option == "eidt") {
    onEdit(command.item);
  }
  if (command.option == "setInfo") {
  }
}

// 设置电子围栏
function onSetElec(row) {
  data.value.userInfo = row;
  data.value.elecProps.visible = true;
  setTimeout(() => {
    initMap();
  }, 200);
}
var map;
var drawingManager;
var polygon;
function initMap() {
  var center = new qq.maps.LatLng(data.value.form.lat, data.value.form.lng);

  //初始化地图
  map = new qq.maps.Map(document.getElementById("container"), {
    rotation: 0, //设置地图旋转角度
    pitch: 0, //设置俯仰角度（0~45）
    zoom: 14, //设置地图缩放级别
    center: center //设置地图中心点坐标
  });

  //画区域
  drawingManager = new qq.maps.drawing.DrawingManager({
    // drawingMode: qq.maps.drawing.OverlayType.POLYGON,
    drawingControl: true,
    drawingControlOptions: {
      position: qq.maps.ControlPosition.TOP_LEFT,
      drawingModes: [qq.maps.drawing.OverlayType.POLYGON]
    },
    selectMode: true
  });
  drawingManager.setMap(map);

  //添加监听事件
  qq.maps.event.addListener(drawingManager, "overlaycomplete", function (e) {
    console.log("user", data.value.userInfo, e.overlay.getPath().elems);
    addBizElectronFence({
      userInfoId: data.value.userInfo.id,
      polygon: JSON.stringify(e.overlay.getPath().elems)
    }).then((res) => {
      mapElectronfence.value.getDataList();
    });
  });
  polygon = new qq.maps.Polygon({
    map: map
  });
  // qq.maps.event.addListener(polygon, "click", function (e) {
  //   console.log(e);
  // });
}
// 读取电子围栏
function setPath(array) {
  var paths = [];
  // for (var i = 0; i < array.length; i++) {
  //   var latlngs = array[i].polygon.split(';');

  //   var path=new qq.maps.LatLng()
  // }

  paths = array.map((arr) => {
    return JSON.parse(arr.polygon).map((item) => {
      return new qq.maps.LatLng(item.lat, item.lng);
    });
  });
  polygon.setPath(paths);
}

function getPosition() {
  var geolocation = new qq.maps.Geolocation(
    "7NRBZ-6VI3O-CXBW5-S7KC2-DB4LF-Y4FFS",
    "referer=mt"
  );
  geolocation.getLocation(showPosition, errorPosition);
}
function showPosition(position) {
  console.log("定位信息", position);
  data.value.form = position;
}
function errorPosition() {
  console.log("定位失败");
  //继续定位
  // this.getPosition();
}
</script>

<template>
  <div>
    <page-main style="height: calc(100vh - 160px); margin: 10px">
      <search-bar>
        <el-form
          :model="data.search"
          size="default"
          label-width="auto"
          label-suffix=""
        >
          <el-row :gutter="30">
            <el-col :span="5">
              <el-form-item label="用户昵称">
                <el-input
                  v-model="data.search.nikeName"
                  placeholder="用户昵称"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="真实姓名">
                <el-input
                  v-model="data.search.name"
                  placeholder="真实姓名"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="电话">
                <el-input
                  v-model="data.search.phone"
                  placeholder="电话"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item>
                <el-button type="primary" @click="currentChange()">
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:search" />
                    </el-icon>
                  </template>
                  查询
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </search-bar>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button-group>
            <el-button type="primary" @click="onAdd">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:circle-plus" />
                </el-icon>
              </template>
              新增
            </el-button>
            <el-button type="danger" @click="onDel">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:close-bold" :size="20" />
                </el-icon>
              </template>
              删除
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>
      <div style="height: calc(100vh - 380px); overflow-y: auto">
        <el-table
          ref="table"
          v-loading="data.loading"
          class="list-table"
          :data="data.dataList"
          border
          highlight-current-row
          row-key="id"
          @sort-change="sortChange"
          @selection-change="data.batch.selectionDataList = $event"
        >
          >
          <el-table-column type="selection" align="center" />
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80"
          />
          <el-table-column prop="avatar" label="头像" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="name" label="真实姓名" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="nikeName" label="昵称" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="phone" label="电话" show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="isShiming"
            label="是否实名"
            show-overflow-tooltip
            width="100"
            align="center"
          >
            <template v-slot="scope">
              <el-tag type="info" v-if="scope.row.isShiming == 0"
                >未实名</el-tag
              >
              <el-tag type="success" v-else>已实名</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="account"
            label="余额"
            show-overflow-tooltip
            align="right"
          >
            <template v-slot="scope">
              ¥ &nbsp;{{
                scope.row.account ? scope.row.account.toFixed(2) : 0.0
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="energyCount"
            label="能量值"
            show-overflow-tooltip
            align="right"
          >
            <template v-slot="scope">
              &nbsp;{{
                scope.row.energyCount ? scope.row.energyCount.toFixed(2) : 0.0
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="tuijianUser"
            label="推荐人"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="type"
            label="用户类型"
            show-overflow-tooltip
            width="100"
            align="center"
          >
            <template v-slot="scope">
              <el-tag type="success" v-if="scope.row.type == 0"
                >普通用户</el-tag
              >
              <el-tag type="warning" v-else>回收员</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="createTime"
            label="创建时间"
            show-overflow-tooltip
            width="140"
            align="center"
            ><template v-slot="scope">
              {{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</template
            >
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button-group>
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="onSetElec(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:number-outlined" />
                    </el-icon>
                  </template>
                  电子围栏</el-button
                >
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
        :current-page="pagination.page"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </page-main>
    <FormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.formModeProps.id"
      v-model="data.formModeProps.visible"
      :mode="data.formMode"
      @success="getDataList"
    />
    <el-dialog
      v-model="data.elecProps.visible"
      v-if="data.elecProps.visible"
      :title="'设置【' + data.userInfo.nikeName + '】回收员的电子围栏'"
      width="78vw"
      top="5vh"
      :close-on-click-modal="false"
      append-to-body
      destroy-on-close
    >
      <el-row :gutter="0">
        <el-col :span="8"
          ><Electronfence
            :userInfoId="data.userInfo.id"
            ref="mapElectronfence"
            :setPolyon="setPath"
          ></Electronfence
        ></el-col>
        <el-col :span="16">
          <div class="container_map">
            <div id="container" style="width: 100vw; height: 70vh"></div>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<style scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  display: flex;
  align-items: center;
  margin-top: 3px;
}
.container_map {
  overflow: hidden;
}
</style>
